package com.lei.datastructure.tree.bst;

import com.lei.datastructure.queue.ListedListQueue;
import com.lei.datastructure.queue.Queue;
import com.lei.datastructure.stack.ArrayStack;
import com.lei.datastructure.stack.Stack;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/14 15:27
 * @Version 1.0
 */
public class BST<E extends Comparable<E>> {

    private Node root;
    private int size;

    public BST() {
        root = null;
        size = 0;
    }

    public void add(E e) {
        root = add(root, e);
//        if (root == null) {
//            root = new Node(e);
//            size++;
//        } else add(root, e);
    }


    public void preOrder() {
        preOrder(root);
        System.out.println("NULL");
    }

    /**
     * 前序遍历
     *
     * @param node 节点
     */
    private void preOrder(Node node) {
        if (node == null) return;
        System.out.print(node.e + "=>");
        preOrder(node.left);
        preOrder(node.right);
    }

    /**
     * 递归实现查找最小值
     *
     * @return 最小值
     */
    public E minimum() {
        if (size == 0) throw new IllegalArgumentException("BST is empty!");
        Node minimum = minimum(root);
        return minimum.e;
    }

    /**
     * 非递归实现查找最小值
     *
     * @return 最小值
     */
    public E minimumRN() {
        if (size == 0) throw new IllegalArgumentException("BST is empty!");
        Stack<Node> stack = new ArrayStack<>();
        Node res = root;
        stack.push(root);
        while (!stack.isEmpty()) {
            res = stack.pop();
            if (res.left != null) stack.push(res.left);
        }
        return res.e;
    }

    private Node minimum(Node node) {
        if (node.left == null)
            return node;
        return minimum(node.left);
    }

    /**
     * 递归实现查找最大值
     *
     * @return 最大值
     */
    public E maximum() {
        if (size == 0) throw new IllegalArgumentException("BST is empty!");
        Node minimum = maximum(root);
        return minimum.e;
    }

    /**
     * 非递归实现查找最大值
     *
     * @return 最大值
     */
    public E maximumRN() {
        if (size == 0) throw new IllegalArgumentException("BST is empty!");
        Stack<Node> stack = new ArrayStack<>();
        Node res = root;
        stack.push(root);
        while (!stack.isEmpty()) {
            res = stack.pop();
            if (res.right != null) stack.push(res.right);
        }
        return res.e;
    }

    /**
     * 从二分搜索树中删除最小值所在的节点
     *
     * @return 返回最小值
     */
    public E removeMin() {
        E ret = minimum();
        root = removeMin(root);
        return ret;
    }

    /**
     * 删除掉以node为根的二分搜索树中的最小节点
     *
     * @param node 节点
     * @return 返回删除节点后新的二分搜索树的根
     */
    private Node removeMin(Node node) {
        // 到树底了 如果有右子树 将其作为左子树
        if (node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            size--;
            return rightNode;
        }
        //如果没到低 那就不是最小值 继续调用
        node.left = removeMin(node.left);
        return node;
    }


    /**
     * 从二分搜索树中删除最大值所在的节点
     *
     * @return 返回最大值
     */
    public E removeMax() {
        E ret = maximum();
        root = removeMax(root);
        return ret;
    }

    /**
     * 删除掉以node为根的二分搜索树中的最大节点
     *
     * @param node 节点
     * @return 返回删除节点后新的二分搜索树的根
     */
    private Node removeMax(Node node) {
        // 到树底了 如果有左子树 将其作为右子树
        if (node.right == null) {
            Node leftNode = node.left;
            node.left = null;
            size--;
            return leftNode;
        }
        //如果没到低 那就不是最小值 继续调用
        node.right = removeMax(node.right);
        return node;
    }


    /**
     * 从二分搜索树中删除元素为e的节点
     *
     * @param e 删除元素
     */
    public void remove(E e) {
        root = remove(root, e);
    }

    /**
     * 删除以node为根的二分搜索树中值为e 的节点
     * 递归算的
     *
     * @param node 节点
     * @param e    删除元素
     * @return root
     */
    private Node remove(Node node, E e) {
        if (node == null) return null;
        if (e.compareTo(node.e) < 0) {
            node.left = remove(node.left, e);
            return node;
        } else if (e.compareTo(node.e) > 0) {
            node.right = remove(node.right, e);
            return node;
        } else {
            if (node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                size--;
                return rightNode;
            }
            if (node.right == null) {
                Node leftNode = node.left;
                node.left = null;
                size--;
                return leftNode;
            }
            // 左右子树都不为空
            Node successor = minimum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;
            node.left = node.right = null;
            return successor;
        }
    }

    private Node maximum(Node node) {
        if (node.right == null)
            return node;
        return maximum(node.right);
    }

    /**
     * 深度遍历 非递归实现
     */
    public void preOrderNR() {
        Stack<Node> stack = new ArrayStack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node current = stack.pop();
            System.out.print(current.e + "=>");
            if (current.right != null)
                stack.push(current.right);
            if (current.left != null)
                stack.push(current.left);
        }
        System.out.println("NULL");
    }

    public void inOrder() {
        inOrder(root);
        System.out.println("NULL");
    }

    /**
     * 广度遍历
     */
    public void levelOrder() {
        Queue<Node> queue = new ListedListQueue<>();
        queue.enqueue(root);
        while (!queue.isEmpty()) {
            Node current = queue.dequeue();
            System.out.print(current.e + "=>");
            if (current.left != null) queue.enqueue(current.left);
            if (current.right != null) queue.enqueue(current.right);
        }
        System.out.println("NULL");
    }

    /**
     * 中序遍历
     *
     * @param node 节点
     */
    private void inOrder(Node node) {
        if (node == null) return;
        inOrder(node.left);
        System.out.print(node.e + "=>");
        inOrder(node.right);
    }


    public void postOrder() {
        postOrder(root);
        System.out.println("NULL");
    }

    /**
     * 中序遍历
     *
     * @param node 节点
     */
    private void postOrder(Node node) {
        if (node == null) return;
        postOrder(node.left);
        postOrder(node.right);
        System.out.print(node.e + "=>");
    }


    public boolean container(E e) {
        return container(root, e);
    }


    private boolean container(Node node, E e) {
        if (node == null) return false;
        if (node.e.compareTo(e) == 0) return true;
        else if (node.e.compareTo(e) < 0) {
            return container(node.left, e);
        } else return container(node.right, e);
    }

    /**
     * 非递归写法
     * 返回插入新节点后的二分搜索树的根
     *
     * @param node 节点
     * @param e    元素
     */
    private void add1(E e) {
        if (root == null) {
            root = new Node(e);
            size++;
            return;
        }
        Node node = root;
        while (node != null) {
            if (e.compareTo(node.e) < 0) {
                node = node.left;
            } else if (e.compareTo(node.e) > 0) {
                node = node.right;
            }
        }
        node = new Node(e);
        size++;
    }

    /**
     * 递归写法
     * 返回插入新节点后的二分搜索树的根
     *
     * @param node 节点
     * @param e    元素
     * @return node
     */
    private Node add(Node node, E e) {
        if (node == null) {
            size++;
            return new Node(e);
        }
        if (e.compareTo(node.e) < 0) node.left = add(node.left, e);
        else if (e.compareTo(node.e) > 0) {
            node.right = add(node.right, e);
        }
        return node;
//        if (e.equals(node.e)) return;
//        else if (e.compareTo(node.e) < 0 && node.left == null) {
//            node.left = new Node(e);
//            size++;
//            return;
//        } else if (e.compareTo(node.e) > 0 && node.right == null) {
//            node.right = new Node(e);
//            size++;
//            return;
//        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        generateBSTString(root, 0, res);
        return res.toString();
    }

    private void generateBSTString(Node node, int depth, StringBuilder res) {
        if (node == null) {
            res.append(generateDepthString(depth)).append("null\n");
            return;
        }
        res.append(generateDepthString(depth)).append(node.e).append("\n");
        generateBSTString(node.left, depth + 1, res);
        generateBSTString(node.right, depth + 1, res);
    }

    private String generateDepthString(int depth) {
        return "--".repeat(Math.max(0, depth));
    }

    private class Node {
        public E e;
        public Node left, right;

        public Node(E e) {
            this.e = e;
            left = null;
            right = null;
        }
    }
}
